package com.test.platform.viewmodel

import ProjectRepository
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.test.platform.model.Project
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ProjectViewModel(
    private val repository: ProjectRepository = ProjectRepository()
) : ViewModel() {
    private val _projects = MutableStateFlow<List<Project>>(emptyList())
    val projects: StateFlow<List<Project>> = _projects.asStateFlow()

    private val _loading = MutableStateFlow(false)
    val loading: StateFlow<Boolean> = _loading.asStateFlow()

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()

    fun loadProjects() {
        viewModelScope.launch(Dispatchers.IO) {
            _loading.value = true
            try {
                val result = repository.getProjects()
                withContext(Dispatchers.Main) {
                    _projects.value = result
                    _error.value = null
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    _error.value = e.message ?: "加载失败"
                }
            } finally {
                withContext(Dispatchers.Main) {
                    _loading.value = false
                }
            }
        }
    }

    fun createProject(project: Project) {
        viewModelScope.launch(Dispatchers.IO) {
            _loading.value = true
            try {
                val result = repository.createProject(project)
                withContext(Dispatchers.Main) {
                    result?.let {
                        loadProjects()
                        _error.value = null
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    _error.value = e.message ?: "创建失败"
                }
            } finally {
                withContext(Dispatchers.Main) {
                    _loading.value = false
                }
            }
        }
    }

    // 添加便捷的创建方法
    fun createProject(
        owner: String,
        name: String,
        description: String? = null,
        gitUrl: String? = null
    ) {
        val project = Project(
            owner = owner,
            name = name,
            description = description,
            gitUrl = gitUrl
        )
        createProject(project)
    }
}